#!/bin/bash

dir_path="/var/lib/docker/private"
file_path="$dir_path/config.yml"
content="
version: 0.1
  log:
    level: debug
  storage:
    filesystem:
    rootdirectory: $dir_path
  http:
    addr: $1
    headers:
      X-Content-Type-Options: [nosniff]
  auth:
    anonymous: true
"

# 判断是否安装docker
if ! command -v docker &> /dev/null
then
  echo "Please manually install Docker. Status 500"
  exit 500
else
  echo "Detect that Docker is installed... "
fi

#启动docker
systemctl start docker
# 判断命令是否执行成功
if [ $? -eq 0 ]; then
    echo "systemctl start docker Execution started successfully."
else
    echo "Failed Execution to systemctl start docker"
fi

# 判断是否有程序占用端口
if ! sudo netstat -tuln | grep ":$1 " > /dev/null
then
  # 使用 test 命令或 [ ] 符号判断目录是否存在
  echo "Check if the $dir_path directory exists... "
  if [ ! -d "$dir_path" ]; then
    # 如果目录不存在，则使用 mkdir 命令创建它
    echo "Directory $dir_path does not exist. Creating now... "
    mkdir -p "$dir_path"
  else
    echo "Directory $dir_path id exist."
  fi
  # 创建本地私有的docker Registry并挂载配置文件等
  echo "Create a local private Docker Registry and mount configuration files, etc... "
  # 将内容写入文件，如果文件已经存在则覆盖它
  echo -e "$content" > "$file_path"
  docker run -d -p $1:$1 --restart=always --name registry -v $dir_path:$dir_path -v $dir_path/config.yml:$dir_path/config.yml registry:2
  echo "Successfully initialized configuration.Status 200"
  exit 200
else
  echo "Port $1 is already occupied, please manually release the program port.Status 500"
  exit 500
fi